<script lang="ts" setup>
import { nextTick, ref } from 'vue'
import ReDialog from '@/components/ReDialog/index.vue'
import { Message } from '@/utils/message'
import { PermissionResponse } from '@/api/types'
import { _addPermission, _updatePermission } from '@/api/auth/menu'
import { permissionFormRules } from './index'
const emit = defineEmits(['afterSuccess'])
const props = defineProps<{
  menuId: number
}>()
const dialogVisible = ref(false)
const title = ref('新增接口权限')
const formRef = ref()
const formState = ref({
  id: undefined,
  name: '',
  permission: '',
  type: '',
  description: ''
})

/**
 * @param data MenuItem 当前选中的菜单menu
 * @param type 0：新增同级菜单，1：新增子菜单
 */
const show = (data?: PermissionResponse) => {
  if (data?.id) {
    title.value = '更新接口权限'
    nextTick(() => {
      formState.value = JSON.parse(JSON.stringify(data))
    })
  } else {
    title.value = '新增接口权限'
  }
  dialogVisible.value = true
}

const handleClose = () => {
  dialogVisible.value = false
  formRef.value.resetFields()
  nextTick(() => {
    console.log(formState.value)
  })
}

const submit = () => {
  formRef.value.validate(valid => {
    if (valid) {
      const { id, name, permission, type, description } = formState.value
      const params = {
        id,
        name,
        permission,
        type,
        description,
        menuId: props.menuId
      }
      const func =
        title.value === '更新接口权限' ? _updatePermission : _addPermission
      func(params)
        .then(() => {
          Message.success('操作成功')
          emit('afterSuccess')
          handleClose()
        })
        .catch(err => {
          Message.error(err.message)
        })
    }
  })
}
defineExpose({
  show
})
</script>

<template>
  <ReDialog
    v-model="dialogVisible"
    :title="title"
    @before-close="handleClose"
    @submit="submit"
  >
    <el-form
      ref="formRef"
      :model="formState"
      :rules="permissionFormRules"
      label-position="right"
      label-width="80px"
    >
      <el-form-item prop="id" hidden />
      <el-form-item label="接口名称" prop="name">
        <el-input v-model="formState.name" placeholder="请输入接口名称" />
      </el-form-item>
      <el-form-item label="接口地址" prop="permission">
        <el-input v-model="formState.permission" placeholder="请输入接口地址" />
      </el-form-item>
      <el-form-item label="类型" prop="type">
        <el-select v-model="formState.type" placeholder="请选择接口类型">
          <el-option label="查询" value="get" />
          <el-option label="新增" value="post" />
          <el-option label="更新" value="patch" />
          <el-option label="删除" value="delete" />
        </el-select>
      </el-form-item>
      <el-form-item label="接口描述" prop="description">
        <el-input
          v-model="formState.description"
          type="textarea"
          :rows="4"
          placeholder="请输入接口描述"
        />
      </el-form-item>
    </el-form>
  </ReDialog>
</template>
